package com.qlyl.modules.information.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qlyl.common.api.vo.Result;
import com.qlyl.common.constant.CommonConstant;
import com.qlyl.common.system.api.ISysBaseAPI;
import com.qlyl.common.system.base.controller.JeecgController;
import com.qlyl.common.system.query.QueryGenerator;
import com.qlyl.common.system.util.JwtUtil;
import com.qlyl.common.util.PasswordUtil;
import com.qlyl.common.util.oConvertUtils;
import com.qlyl.modules.information.entity.Consumers;
import com.qlyl.modules.information.service.IConsumersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Slf4j
@RequestMapping("/consumers")
@RestController
public class ConsumersController extends JeecgController<Consumers, IConsumersService> {

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Autowired
    private IConsumersService consumersService;


    /**
     * 生成在添加用户情况下没有主键的问题,返回给前端
     *
     * @return
     */
    @RequestMapping(value = "/generateUserId", method = RequestMethod.GET)
    public Result<String> generateUserId() {
        Result<String> result = new Result<>();
        System.out.println("我执行了,生成用户ID==============================");
        String userId = UUID.randomUUID().toString().replace("-", "");
        result.setSuccess(true);
        result.setResult(userId);
        return result;
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<IPage<Consumers>> queryPageList(Consumers consumers, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        Result<IPage<Consumers>> result = new Result<IPage<Consumers>>();
        QueryWrapper<Consumers> queryWrapper = QueryGenerator.initQueryWrapper(consumers, req.getParameterMap());
        Page<Consumers> page = new Page<Consumers>(pageNo, pageSize);
        IPage<Consumers> pageList = consumersService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
/*
    @RequiresPermissions("consumers:add")
*/
    public Result<Consumers> add(@RequestBody JSONObject jsonObject) {
        Result<Consumers> result = new Result<Consumers>();
        try {
            Consumers consumers = JSON.parseObject(jsonObject.toJSONString(), Consumers.class);
            consumers.setCreateTime(new Date());//设置创建时间
            consumers.setCompanyStatus(1);
            consumers.setCheckStatus(1);
            consumers.setDelFlag(0);
            consumersService.save(consumers);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
//    @RequiresPermissions("consumers:edit")
    public Result<Consumers> edit(@RequestBody JSONObject jsonObject) {
        Result<Consumers> result = new Result<Consumers>();
        try {
            Consumers consumers = consumersService.getById(jsonObject.getString("id"));
            sysBaseAPI.addLog("编辑企业信息，id： " + jsonObject.getString("id"), CommonConstant.LOG_TYPE_2, 2);
            if (consumers == null) {
                result.error500("未找到对应实体");
            } else {
                Consumers editConsumers = JSON.parseObject(jsonObject.toJSONString(), Consumers.class);
                editConsumers.setUpdateTime(new Date());
                editConsumers.setCheckStatus(1);
                consumersService.updateById(editConsumers);
                result.success("修改成功!");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        sysBaseAPI.addLog("删除企业信息，id： " + id, CommonConstant.LOG_TYPE_2, 3);
        this.consumersService.removeById(id);
        return Result.ok("删除成功");
    }

    /**
     * 批量删除用户
     */
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        sysBaseAPI.addLog("批量删除企业信息， ids： " + ids, CommonConstant.LOG_TYPE_2, 3);
        this.consumersService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除企业成功");
    }

    /**
     * 冻结&解冻用户
     *
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/frozenBatch", method = RequestMethod.PUT)
    public Result<Consumers> frozenBatch(@RequestBody JSONObject jsonObject) {
        Result<Consumers> result = new Result<Consumers>();
        try {
            String ids = jsonObject.getString("ids");
            String status = jsonObject.getString("companyStatus");
            String[] arr = ids.split(",");
            for (String id : arr) {
                if (oConvertUtils.isNotEmpty(id)) {
                    this.consumersService.update(new Consumers().setCompanyStatus(Integer.valueOf(status)),
                            new UpdateWrapper<Consumers>().lambda().eq(Consumers::getId, id));
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败" + e.getMessage());
        }
        result.success("操作成功!");
        return result;

    }

    /**
     * 审核企业信息
     *
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/frozenBatchChcek")
    public Result<Consumers> frozenBatchChcek(@RequestBody JSONObject jsonObject) {
        Result<Consumers> result = new Result<Consumers>();
        String ids = jsonObject.getString("ids");
        String checkStatus = jsonObject.getString("checkStatus");
        boolean flag = consumersService.frozenBatchChcek(ids,checkStatus);
        if(flag){
            result.success("操作成功!");
        }else{
            result.error500("操作失败");
        }
        return result;

    }


    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result<Consumers> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<Consumers> result = new Result<Consumers>();
        Consumers  consumers = consumersService.getById(id);
        if (consumers == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(consumers);
            result.setSuccess(true);
        }
        return result;
    }


    /**
     * 校验企业是否唯一<br>
     * 可以校验其他 需要检验什么就传什么。。。
     *
     * @param consumers
     * @return
     */
    @RequestMapping(value = "/checkOnlyConsumers", method = RequestMethod.GET)
    public Result<Boolean> checkOnlyConsumers(Consumers consumers) {
        Result<Boolean> result = new Result<>();
        //如果此参数为false则程序发生异常
        result.setResult(true);
        try {
            //通过传入信息查询新的企业信息
            Consumers newConsumers = consumersService.getOne(new QueryWrapper<Consumers>(consumers));
            if (newConsumers != null) {
                result.setSuccess(false);
                result.setMessage("用户账号已存在");
                return result;
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            return result;
        }
        result.setSuccess(true);
        return result;
    }





//    /**
//     * 生成在添加用户情况下没有主键的问题,返回给前端,根据该id绑定部门数据
//     *
//     * @return
//     */
//    @RequestMapping(value = "/generateUserId", method = RequestMethod.GET)
//    public Result<String> generateUserId() {
//        Result<String> result = new Result<>();
//        System.out.println("我执行了,生成用户ID==============================");
//        String userId = UUID.randomUUID().toString().replace("-", "");
//        result.setSuccess(true);
//        result.setResult(userId);
//        return result;
//    }



    /**
     * 导出excel
     * @param consumers
     * @param request
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(Consumers consumers, HttpServletRequest request) {

        return exportXls(request,consumers,Consumers.class,"企业信息列表");

    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("consumers:import")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return importExcel(request,response,Consumers.class);
    }

    /**
     * @param consumersIds
     * @return
     * @功能：根据id 批量查询
     */
    @RequestMapping(value = "/queryByIds", method = RequestMethod.GET)
    public Result<Collection<Consumers>> queryByIds(@RequestParam String consumersIds) {
        Result<Collection<Consumers>> result = new Result<>();
        String[] consumersId = consumersIds.split(",");
        Collection<String> idList = Arrays.asList(consumersId);
        Collection<Consumers> consumersList = consumersService.listByIds(idList);
        result.setSuccess(true);
        result.setResult(consumersList);
        return result;
    }



//    /**
//     * 用户注册接口
//     *
//     * @param jsonObject
//     * @param consumers
//     * @return
//     */
//    @PostMapping("/register")
//    public Result<JSONObject> consumersRegister(@RequestBody JSONObject jsonObject, Consumers consumers) {
//        Result<JSONObject> result = new Result<JSONObject>();
//        String cphone = jsonObject.getString("cphone");
//        String smscode = jsonObject.getString("smscode");
//        Object code = redisUtil.get(cphone);
//        String username = jsonObject.getString("username");
//        String password = jsonObject.getString("password");
//        String email = jsonObject.getString("email");
//        SysUser sysUser1 = sysUserService.getUserByName(username);
//        if (sysUser1 != null) {
//            result.setMessage("用户名已注册");
//            result.setSuccess(false);
//            return result;
//        }
//        SysUser sysUser2 = sysUserService.getUserBycphone(cphone);
//
//        if (sysUser2 != null) {
//            result.setMessage("该手机号已注册");
//            result.setSuccess(false);
//            return result;
//        }
//        SysUser sysUser3 = sysUserService.getUserByEmail(email);
//        if (sysUser3 != null) {
//            result.setMessage("邮箱已被注册");
//            result.setSuccess(false);
//            return result;
//        }
//
//        if (!smscode.equals(code)) {
//            result.setMessage("手机验证码错误");
//            result.setSuccess(false);
//            return result;
//        }
//
//        try {
//            user.setCreateTime(new Date());// 设置创建时间
//            String salt = oConvertUtils.randomGen(8);
//            String passwordEncode = PasswordUtil.encrypt(username, password, salt);
//            user.setSalt(salt);
//            user.setUsername(username);
//            user.setRealname(username);
//            user.setPassword(passwordEncode);
//            user.setEmail(email);
//            user.setcphone(cphone);
//            user.setStatus(1);
//            user.setDelFlag(CommonConstant.DEL_FLAG_0.toString());
//            user.setActivitiSync(CommonConstant.ACT_SYNC_1);
//            sysUserService.addUserWithRole(user, "ee8626f80f7c2619917b6236f3a7f02b");//默认临时角色 test
//            result.success("注册成功");
//        } catch (Exception e) {
//            result.error500("注册失败");
//        }
//        return result;
//    }



//    /**
//     * 用户手机号验证
//     */
//    @PostMapping("/cphoneVerification")
//    public Result<String> cphoneVerification(@RequestBody JSONObject jsonObject) {
//        Result<String> result = new Result<String>();
//        String cphone = jsonObject.getString("cphone");
//        String smscode = jsonObject.getString("smscode");
//        Object code = redisUtil.get(cphone);
//        if (!smscode.equals(code)) {
//            result.setMessage("手机验证码错误");
//            result.setSuccess(false);
//            return result;
//        }
//        redisUtil.set(cphone, smscode);
//        result.setResult(smscode);
//        result.setSuccess(true);
//        return result;
//    }

//    /**
//     * 用户更改密码
//     */
//    @GetMapping("/passwordChange")
//    public Result<SysUser> passwordChange(@RequestParam(name = "username") String username,
//                                          @RequestParam(name = "password") String password,
//                                          @RequestParam(name = "smscode") String smscode,
//                                          @RequestParam(name = "cphone") String cphone) {
//        Result<SysUser> result = new Result<SysUser>();
//        SysUser sysUser = new SysUser();
//        Object object = redisUtil.get(cphone);
//        if (null == object) {
//            result.setMessage("更改密码失败");
//            result.setSuccess(false);
//        }
//        if (!smscode.equals(object)) {
//            result.setMessage("更改密码失败");
//            result.setSuccess(false);
//        }
//        sysUser = this.sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));
//        if (sysUser == null) {
//            result.setMessage("未找到对应实体");
//            result.setSuccess(false);
//            return result;
//        } else {
//            String salt = oConvertUtils.randomGen(8);
//            sysUser.setSalt(salt);
//            String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), password, salt);
//            sysUser.setPassword(passwordEncode);
//            this.sysUserService.updateById(sysUser);
//            result.setSuccess(true);
//            result.setMessage("密码修改完成！");
//            return result;
//        }
//    }




//    /**
//     * 获取用户列表  根据用户名和真实名 模糊匹配
//     *
//     * @param keyword
//     * @param pageNo
//     * @param pageSize
//     * @return
//     */
//    @GetMapping("/appUserList")
//    public Result<?> appUserList(@RequestParam(name = "keyword", required = false) String keyword,
//                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
//                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
//        try {
//            //TODO 从查询效率上将不要用mp的封装的page分页查询 建议自己写分页语句
//            LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<SysUser>();
//            query.eq(SysUser::getActivitiSync, "1");
//            query.eq(SysUser::getDelFlag, "0");
//            query.and(i -> i.like(SysUser::getUsername, keyword).or().like(SysUser::getRealname, keyword));
//
//            Page<SysUser> page = new Page<>(pageNo, pageSize);
//            IPage<SysUser> res = this.sysUserService.page(page, query);
//            return Result.ok(res);
//        } catch (Exception e) {
//            log.error(e.getMessage(), e);
//            return Result.error(500, "查询失败:" + e.getMessage());
//        }
//
//    }


}
